import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:hi_net/model/local_data.dart';
import 'package:hi_net/widget/hi_banner.dart';

import '../core/hi_base_tab_state.dart';
import '../http/dio/home_dao.dart';
import '../model/home_mo.dart';
import '../model/video_model.dart';
import '../widget/video_card.dart';

class HomeTabPage extends StatefulWidget {
  final String categoryName;
  final List<BannerMo> bannerList;

  const HomeTabPage({super.key, required this.categoryName, required this.bannerList});

  @override
  State<HomeTabPage> createState() => _HomeTabPageState();
}

class _HomeTabPageState extends HiBaseTabState<HomeMo, VideoModel, HomeTabPage> {
  @override
  get contentChild => StaggeredGridView.countBuilder(
        controller: scrollController,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        crossAxisCount: 2,
        itemCount: dataList.length,
        itemBuilder: (BuildContext context, int index) {
          //有banner时第一个item位置显示banner
          if (widget.bannerList.isNotEmpty && index == 0) {
            return _banner();
          }
          return VideoCard(videoModel: dataList[index]);
        },
        staggeredTileBuilder: (int index) {
          if (widget.bannerList.isNotEmpty && index == 0) {
            return const StaggeredTile.fit(2);
          }
          return const StaggeredTile.fit(1);
        },
      );

  Widget _banner() {
    return HiBanner(bannerList: widget.bannerList, padding: const EdgeInsets.all(5));
  }

  @override
  Future<HomeMo> getData(int pageIndex) async {
    HomeMo result = await HomeDao.get(widget.categoryName, pageIndex: pageIndex, pageSize: 10);
    return result;
  }

  @override
  List<VideoModel> parseList(HomeMo result) {
    return result.videoList;
  }

  @override
  void loadError(loadMore) {
    super.loadError(loadMore);
    List<VideoModel> list = getVideos();
    setState(() {
      if (loadMore) {
        if (list.isNotEmpty) {
          //合成一个新数组
          dataList = [...dataList, ...list];
          pageIndex++;
        }
      } else {
        dataList = list;
      }
    });
  }
}
